//
//  ViewController.m
//  epCloud
//
//  Created by jd on 2019/3/29.
//  Copyright © 2019 jd. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "utils/Masonry/Masonry.h"
#import "utils/SVProgressHUD/SVProgressHUD.h"

@interface ViewController ()<WKNavigationDelegate,UIWebViewDelegate>
@property (strong, nonatomic) WKWebView *mainWebView;
@property (strong, nonatomic) UIImageView *loadImageView;

@property (nonatomic, strong) NSString *urlStr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLoadImageView];
    [self initWebView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}
#pragma mark - init
- (void)initLoadImageView
{
    CGSize viewSize = self.view.bounds.size;
    UIInterfaceOrientation sataus = [UIApplication sharedApplication].statusBarOrientation;
    NSString *viewOrientation = nil;
    if (sataus == UIInterfaceOrientationLandscapeLeft || sataus == UIInterfaceOrientationLandscapeRight) {
        viewOrientation = @"Landscape";
    }
    else
    {
        viewOrientation = @"Portrait";
    }
    NSString *launchImage = nil;
    
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    
    NSError *error = nil;
    NSData *jsonData = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"AppSetting" ofType:@"json"]];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    
    if (jsonObject != nil && error == nil && jsonObject[@"baseURL"]){
        self.urlStr = jsonObject[@"baseURL"];
        self.loadImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:launchImage]];
        self.loadImageView.frame = self.view.bounds;
        [[self frontWindow] addSubview:self.loadImageView];
    }else{
        // 解析错误
        [self showMessage:@"解析错误"];
        return;
    }
}
- (void)initWebView
{
    self.mainWebView = [[WKWebView alloc]init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
    if ([UIScrollView instancesRespondToSelector:@selector(contentInsetAdjustmentBehavior)]) {
        self.mainWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.mainWebView.scrollView.bounces = NO;
    self.mainWebView.navigationDelegate = self;
    [self.mainWebView loadRequest:request];
    [self.view addSubview:self.mainWebView];
    [self.mainWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.mas_topLayoutGuide).with.offset(0);
            make.bottom.equalTo(self.mas_bottomLayoutGuide).with.offset(0);
        } else {
            make.top.equalTo(self.view.mas_top).with.offset(0);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        }
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
    }];
}
#pragma mark - webview delegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"-------页面开始加载时调用-------");
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    if([error code] == NSURLErrorCancelled)
    {
        return;
    }
    NSLog(@"-------数据加载发生错误时调用:%@-------",error.localizedDescription);
    self.loadImageView.hidden = YES;
    [self showMessage:error.localizedDescription];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    if([error code] == NSURLErrorCancelled)
    {
        return;
    }
    NSLog(@"-------数据加载发生错误时调用:%@-------",error.localizedDescription);
    self.loadImageView.hidden = YES;
    [self showMessage:error.localizedDescription];
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    NSLog(@"-------页面结束加载时调用-------");
    self.loadImageView.hidden = YES;
}
#pragma mark - mask
- (void)showMessage:(NSString*)text
{
    [SVProgressHUD showErrorWithStatus:text];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD dismissWithDelay:1.6 completion:nil];
}
- (UIWindow *)frontWindow {
    NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows) {
        BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
        BOOL windowIsVisible = !window.hidden && window.alpha > 0;
        BOOL windowLevelSupported = (window.windowLevel >= UIWindowLevelNormal && window.windowLevel <= UIWindowLevelNormal);
        BOOL windowKeyWindow = window.isKeyWindow;
        
        if(windowOnMainScreen && windowIsVisible && windowLevelSupported && windowKeyWindow) {
            return window;
        }
    }
    return nil;
}

@end
